<template>
  <view class="container">
    <!-- 加载状态 -->
    <view v-if="loading" class="loading-container">
      <uni-load-more status="loading" :content-text="loadText"></uni-load-more>
    </view>

    <!-- 监控内容 -->
    <view v-else class="content-container">
      <!-- CPU 监控 -->
      <view class="monitor-section">
        <uni-card :is-shadow="false" :border="true">
          <template v-slot:title>
            <view class="card-title">
              <uni-icons type="gear-filled" size="20" color="#1890ff"></uni-icons>
              <text class="title-text">CPU 监控</text>
            </view>
          </template>

          <view class="cpu-content" v-if="serverData.cpu">
            <view class="cpu-overview">
              <view class="cpu-usage">
                <text class="usage-label">CPU使用率</text>
                <text class="usage-value">{{ (100 - parseFloat(serverData.cpu.free || 0)).toFixed(1) }}%</text>
                <uni-progress
                    :percent="100 - parseFloat(serverData.cpu.free || 0)"
                    :active="true"
                    :active-color="getCpuColor(100 - parseFloat(serverData.cpu.free || 0))"
                    :show-info="false"
                    stroke-width="8">
                </uni-progress>
              </view>
            </view>

            <view class="info-grid">
              <view class="info-item">
                <text class="info-label">核心数</text>
                <text class="info-value">{{ serverData.cpu.cpuNum || 'N/A' }}</text>
              </view>
              <view class="info-item">
                <text class="info-label">用户使用率</text>
                <text class="info-value">{{ serverData.cpu.used || 'N/A' }}%</text>
              </view>
              <view class="info-item">
                <text class="info-label">系统使用率</text>
                <text class="info-value">{{ serverData.cpu.sys || 'N/A' }}%</text>
              </view>
              <view class="info-item">
                <text class="info-label">当前空闲率</text>
                <text class="info-value free-rate">{{ serverData.cpu.free || 'N/A' }}%</text>
              </view>
            </view>
          </view>
        </uni-card>
      </view>

      <!-- 内存监控 -->
      <view class="monitor-section">
        <uni-card :is-shadow="false" :border="true">
          <template v-slot:title>
            <view class="card-title">
              <uni-icons type="staff-filled" size="20" color="#52c41a"></uni-icons>
              <text class="title-text">内存监控</text>
            </view>
          </template>

          <view class="memory-content">
            <!-- 系统内存 -->
            <view class="memory-section" v-if="serverData.mem">
              <view class="memory-header">
                <text class="memory-title">系统内存</text>
                <view class="memory-usage">
                  <text class="usage-percent" :class="{ 'text-danger': serverData.mem.usage > 80 }">
                    {{ serverData.mem.usage || 0 }}%
                  </text>
                  <uni-progress
                      :percent="parseFloat(serverData.mem.usage || 0)"
                      :active="true"
                      :active-color="getMemoryColor(parseFloat(serverData.mem.usage || 0))"
                      :show-info="false"
                      stroke-width="6">
                  </uni-progress>
                </view>
              </view>
              <view class="memory-details">
                <view class="memory-item">
                  <text class="label">总内存：</text>
                  <text class="value">{{ serverData.mem.total || 'N/A' }}G</text>
                </view>
                <view class="memory-item">
                  <text class="label">已用内存：</text>
                  <text class="value">{{ serverData.mem.used || 'N/A' }}G</text>
                </view>
                <view class="memory-item">
                  <text class="label">剩余内存：</text>
                  <text class="value">{{ serverData.mem.free || 'N/A' }}G</text>
                </view>
              </view>
            </view>

            <!-- JVM内存 -->
            <view class="memory-section" v-if="serverData.jvm">
              <view class="memory-header">
                <text class="memory-title">JVM内存</text>
                <view class="memory-usage">
                  <text class="usage-percent" :class="{ 'text-danger': serverData.jvm.usage > 80 }">
                    {{ serverData.jvm.usage || 0 }}%
                  </text>
                  <uni-progress
                      :percent="parseFloat(serverData.jvm.usage || 0)"
                      :active="true"
                      :active-color="getMemoryColor(parseFloat(serverData.jvm.usage || 0))"
                      :show-info="false"
                      stroke-width="6">
                  </uni-progress>
                </view>
              </view>
              <view class="memory-details">
                <view class="memory-item">
                  <text class="label">总内存：</text>
                  <text class="value">{{ serverData.jvm.total || 'N/A' }}M</text>
                </view>
                <view class="memory-item">
                  <text class="label">已用内存：</text>
                  <text class="value">{{ serverData.jvm.used || 'N/A' }}M</text>
                </view>
                <view class="memory-item">
                  <text class="label">剩余内存：</text>
                  <text class="value">{{ serverData.jvm.free || 'N/A' }}M</text>
                </view>
              </view>
            </view>
          </view>
        </uni-card>
      </view>

      <!-- 服务器信息 -->
      <view class="monitor-section">
        <uni-card :is-shadow="false" :border="true">
          <template v-slot:title>
            <view class="card-title">
              <uni-icons type="gear" size="20" color="#fa8c16"></uni-icons>
              <text class="title-text">服务器信息</text>
            </view>
          </template>

          <view class="server-info" v-if="serverData.sys">
            <view class="info-grid">
              <view class="info-item">
                <text class="info-label">服务器名称</text>
                <text class="info-value server-name">{{ serverData.sys.computerName || 'N/A' }}</text>
              </view>
              <view class="info-item">
                <text class="info-label">服务器IP</text>
                <text class="info-value ip-address">{{ serverData.sys.computerIp || 'N/A' }}</text>
              </view>
              <view class="info-item">
                <text class="info-label">操作系统</text>
                <text class="info-value">{{ serverData.sys.osName || 'N/A' }}</text>
              </view>
              <view class="info-item">
                <text class="info-label">系统架构</text>
                <text class="info-value">{{ serverData.sys.osArch || 'N/A' }}</text>
              </view>
            </view>
          </view>
        </uni-card>
      </view>

      <!-- Java虚拟机信息 -->
      <view class="monitor-section">
        <uni-card :is-shadow="false" :border="true">
          <template v-slot:title>
            <view class="card-title">
              <uni-icons type="compose" size="20" color="#722ed1"></uni-icons>
              <text class="title-text">Java虚拟机信息</text>
            </view>
          </template>

          <view class="jvm-info" v-if="serverData.jvm">
            <view class="jvm-overview">
              <view class="jvm-item">
                <text class="jvm-label">Java名称：</text>
                <text class="jvm-value">{{ serverData.jvm.name || 'N/A' }}</text>
              </view>
              <view class="jvm-item">
                <text class="jvm-label">Java版本：</text>
                <text class="jvm-value">{{ serverData.jvm.version || 'N/A' }}</text>
              </view>
              <view class="jvm-item">
                <text class="jvm-label">启动时间：</text>
                <text class="jvm-value">{{ serverData.jvm.startTime || 'N/A' }}</text>
              </view>
              <view class="jvm-item">
                <text class="jvm-label">运行时长：</text>
                <text class="jvm-value runtime">{{ serverData.jvm.runTime || 'N/A' }}</text>
              </view>
            </view>

            <view class="jvm-paths">
              <view class="path-item">
                <text class="path-label">安装路径：</text>
                <text class="path-value" @click="handleCopy(serverData.jvm.home, 'Java安装路径')">
                  {{ serverData.jvm.home || 'N/A' }}
                </text>
              </view>
              <view class="path-item" v-if="serverData.sys">
                <text class="path-label">项目路径：</text>
                <text class="path-value" @click="handleCopy(serverData.sys.userDir, '项目路径')">
                  {{ serverData.sys.userDir || 'N/A' }}
                </text>
              </view>
              <view class="path-item">
                <text class="path-label">运行参数：</text>
                <text class="path-value args" @click="handleCopy(serverData.jvm.inputArgs, 'JVM运行参数')">
                  {{ serverData.jvm.inputArgs || 'N/A' }}
                </text>
              </view>
            </view>
          </view>
        </uni-card>
      </view>

      <!-- 磁盘状态 -->
      <view class="monitor-section">
        <uni-card :is-shadow="false" :border="true">
          <template v-slot:title>
            <view class="card-title">
              <uni-icons type="folder-add" size="20" color="#eb2f96"></uni-icons>
              <text class="title-text">磁盘状态</text>
            </view>
          </template>

          <view class="disk-content" v-if="serverData.sysFiles && serverData.sysFiles.length > 0">
            <view v-for="(disk, index) in serverData.sysFiles" :key="index" class="disk-item">
              <view class="disk-header">
                <view class="disk-info">
                  <text class="disk-name">{{ disk.dirName || 'N/A' }}</text>
                  <text class="disk-type">{{ disk.typeName || 'N/A' }}</text>
                </view>
                <view class="disk-usage">
                  <text class="usage-percent" :class="{ 'text-danger': parseFloat(disk.usage) > 80 }">
                    {{ disk.usage || 0 }}%
                  </text>
                </view>
              </view>

              <uni-progress
                  :percent="parseFloat(disk.usage || 0)"
                  :active="true"
                  :active-color="getDiskColor(parseFloat(disk.usage || 0))"
                  :show-info="false"
                  stroke-width="6">
              </uni-progress>

              <view class="disk-details">
                <view class="disk-detail-item">
                  <text class="detail-label">文件系统：</text>
                  <text class="detail-value">{{ disk.sysTypeName || 'N/A' }}</text>
                </view>
                <view class="disk-detail-item">
                  <text class="detail-label">总大小：</text>
                  <text class="detail-value">{{ disk.total || 'N/A' }}</text>
                </view>
                <view class="disk-detail-item">
                  <text class="detail-label">可用大小：</text>
                  <text class="detail-value free-size">{{ disk.free || 'N/A' }}</text>
                </view>
                <view class="disk-detail-item">
                  <text class="detail-label">已用大小：</text>
                  <text class="detail-value used-size">{{ disk.used || 'N/A' }}</text>
                </view>
              </view>
            </view>
          </view>

          <view v-else class="no-disk-data">
            <uni-icons type="info" size="40" color="#ccc"></uni-icons>
            <text class="no-data-text">暂无磁盘数据</text>
          </view>
        </uni-card>
      </view>

      <!-- 最后更新时间 -->
      <view class="update-time">
        <text class="update-text">最后更新：{{ lastUpdateTime }}</text>
      </view>
    </view>

    <!-- 错误状态 -->
    <view v-if="error && !loading" class="error-container">
      <uni-icons type="info" size="40" color="#ccc"></uni-icons>
      <text class="error-text">{{ errorMessage }}</text>
      <button class="retry-btn" @click="getServerData">重新加载</button>
    </view>
  </view>
</template>

<script setup>
import {getCurrentInstance, onMounted, ref} from 'vue'
import {getServer} from '@/api/monitor/server'
import {parseTime} from '@/utils/ruoyi'

const {proxy} = getCurrentInstance()

// 数据定义
const serverData = ref({})
const loading = ref(true)
const error = ref(false)
const errorMessage = ref('加载失败，请重试')
const lastUpdateTime = ref('')

// 加载文本配置
const loadText = {
  contentdown: '上拉显示更多',
  contentrefresh: '正在加载服务监控数据，请稍候！',
  contentnomore: '没有更多数据了'
}

// 页面加载
onMounted(() => {
  getServerData()
  // 设置定时刷新（每30秒）
  setInterval(() => {
    if (!loading.value) {
      getServerData()
    }
  }, 30000)
})

// 获取服务器数据
async function getServerData() {
  loading.value = true
  error.value = false

  try {
    const response = await getServer()
    if (response.code === 200) {
      serverData.value = response.data || {}
      lastUpdateTime.value = parseTime(new Date(), '{y}-{m}-{d} {h}:{i}:{s}')
    } else {
      error.value = true
      errorMessage.value = response.msg || '获取服务器数据失败'
    }
  } catch (err) {
    console.error('获取服务器数据失败:', err)
    error.value = true
    errorMessage.value = '网络错误，请检查网络连接'
  } finally {
    loading.value = false
  }
}

// 刷新数据
function handleRefresh() {
  getServerData()
  proxy.$modal.showToast('正在刷新...')
}

// 返回上一页
function handleBack() {
  uni.navigateBack()
}

// 复制内容
function handleCopy(content, type) {
  if (!content || content === 'N/A') {
    proxy.$modal.showToast('无内容可复制')
    return
  }

  uni.setClipboardData({
    data: content,
    success: () => {
      proxy.$modal.showToast(`${type}已复制到剪贴板`)
    },
    fail: () => {
      proxy.$modal.showToast('复制失败')
    }
  })
}

// 获取CPU颜色
function getCpuColor(usage) {
  if (usage > 80) return '#ff4d4f'
  if (usage > 60) return '#fa8c16'
  return '#52c41a'
}

// 获取内存颜色
function getMemoryColor(usage) {
  if (usage > 80) return '#ff4d4f'
  if (usage > 60) return '#fa8c16'
  return '#52c41a'
}

// 获取磁盘颜色
function getDiskColor(usage) {
  if (usage > 80) return '#ff4d4f'
  if (usage > 60) return '#fa8c16'
  return '#52c41a'
}
</script>

<style lang="scss" scoped>
.container {
  min-height: 100vh;
  background-color: #f5f5f5;
}

.refresh-btn {
  background: transparent;
  border: none;
  padding: 4px;
}

.loading-container, .error-container {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  min-height: 50vh;
  padding: 20px;
}

.error-container {
  .error-text {
    margin: 15px 0;
    color: #999;
    font-size: 14px;
  }

  .retry-btn {
    background-color: #007aff;
    color: #fff;
    border: none;
    border-radius: 4px;
    padding: 8px 16px;
    font-size: 14px;
  }
}

.content-container {
  padding: 0 0 20px 0;
}

.monitor-section {
  margin-bottom: 10px;
}

.card-title {
  display: flex;
  align-items: center;
  gap: 8px;

  .title-text {
    font-size: 16px;
    font-weight: bold;
    color: #333;
  }
}

// CPU监控样式
.cpu-content {
  padding: 15px 0;

  .cpu-overview {
    margin-bottom: 20px;

    .cpu-usage {
      .usage-label {
        font-size: 14px;
        color: #666;
        display: block;
        margin-bottom: 5px;
      }

      .usage-value {
        font-size: 24px;
        font-weight: bold;
        color: #1890ff;
        display: block;
        margin-bottom: 10px;
      }
    }
  }

  .info-grid {
    display: grid;
    grid-template-columns: 1fr 1fr;
    gap: 15px;

    .info-item {
      display: flex;
      flex-direction: column;
      gap: 4px;

      .info-label {
        font-size: 12px;
        color: #666;
      }

      .info-value {
        font-size: 14px;
        color: #333;
        font-weight: 500;

        &.free-rate {
          color: #52c41a;
        }
      }
    }
  }
}

// 内存监控样式
.memory-content {
  padding: 15px 0;

  .memory-section {
    margin-bottom: 20px;

    &:last-child {
      margin-bottom: 0;
    }

    .memory-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
      margin-bottom: 10px;

      .memory-title {
        font-size: 14px;
        font-weight: bold;
        color: #333;
      }

      .memory-usage {
        display: flex;
        align-items: center;
        gap: 10px;
        flex: 1;
        margin-left: 20px;

        .usage-percent {
          font-size: 16px;
          font-weight: bold;
          color: #52c41a;
          min-width: 40px;
          text-align: right;

          &.text-danger {
            color: #ff4d4f;
          }
        }
      }
    }

    .memory-details {
      padding-left: 10px;
      border-left: 3px solid #e8e8e8;

      .memory-item {
        display: flex;
        justify-content: space-between;
        padding: 4px 0;

        .label {
          font-size: 13px;
          color: #666;
        }

        .value {
          font-size: 13px;
          color: #333;
          font-weight: 500;
        }
      }
    }
  }
}

// 服务器信息样式
.server-info {
  padding: 15px 0;

  .info-grid {
    display: grid;
    grid-template-columns: 1fr;
    gap: 12px;

    .info-item {
      display: flex;
      justify-content: space-between;
      align-items: center;
      padding: 8px 0;
      border-bottom: 1px solid #f0f0f0;

      &:last-child {
        border-bottom: none;
      }

      .info-label {
        font-size: 14px;
        color: #666;
        min-width: 80px;
      }

      .info-value {
        font-size: 14px;
        color: #333;
        flex: 1;
        text-align: right;

        &.server-name {
          color: #1890ff;
          font-weight: 500;
        }

        &.ip-address {
          color: #fa8c16;
          font-family: 'Courier New', monospace;
        }
      }
    }
  }
}

// JVM信息样式
.jvm-info {
  padding: 15px 0;

  .jvm-overview {
    margin-bottom: 15px;

    .jvm-item {
      display: flex;
      justify-content: space-between;
      padding: 6px 0;
      border-bottom: 1px solid #f0f0f0;

      &:last-child {
        border-bottom: none;
      }

      .jvm-label {
        font-size: 13px;
        color: #666;
      }

      .jvm-value {
        font-size: 13px;
        color: #333;

        &.runtime {
          color: #52c41a;
          font-weight: 500;
        }
      }
    }
  }

  .jvm-paths {
    .path-item {
      margin-bottom: 12px;

      .path-label {
        font-size: 13px;
        color: #666;
        display: block;
        margin-bottom: 4px;
      }

      .path-value {
        font-size: 12px;
        color: #1890ff;
        word-break: break-all;
        line-height: 1.4;
        font-family: 'Courier New', monospace;

        &.args {
          background-color: #f6f8fa;
          padding: 8px;
          border-radius: 4px;
          border: 1px solid #e1e4e8;
        }
      }
    }
  }
}

// 磁盘状态样式
.disk-content {
  padding: 15px 0;

  .disk-item {
    margin-bottom: 20px;
    padding-bottom: 15px;
    border-bottom: 1px solid #f0f0f0;

    &:last-child {
      margin-bottom: 0;
      border-bottom: none;
    }

    .disk-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
      margin-bottom: 8px;

      .disk-info {
        .disk-name {
          font-size: 16px;
          font-weight: bold;
          color: #333;
          display: block;
          margin-bottom: 2px;
        }

        .disk-type {
          font-size: 12px;
          color: #666;
        }
      }

      .disk-usage {
        .usage-percent {
          font-size: 18px;
          font-weight: bold;
          color: #52c41a;

          &.text-danger {
            color: #ff4d4f;
          }
        }
      }
    }

    .disk-details {
      margin-top: 10px;
      display: grid;
      grid-template-columns: 1fr 1fr;
      gap: 8px;

      .disk-detail-item {
        display: flex;
        flex-direction: column;

        .detail-label {
          font-size: 12px;
          color: #666;
        }

        .detail-value {
          font-size: 13px;
          color: #333;
          font-weight: 500;

          &.free-size {
            color: #52c41a;
          }

          &.used-size {
            color: #fa8c16;
          }
        }
      }
    }
  }
}

.no-disk-data {
  display: flex;
  flex-direction: column;
  align-items: center;
  padding: 40px 0;

  .no-data-text {
    margin-top: 10px;
    color: #999;
    font-size: 14px;
  }
}

.update-time {
  padding: 20px;
  text-align: center;

  .update-text {
    font-size: 12px;
    color: #999;
  }
}

.text-danger {
  color: #ff4d4f !important;
}
</style>